package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.BeanUtils;
import org.jeecg.modules.system.entity.Application;
import org.jeecg.modules.system.entity.SysRoleApp;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.IApplicationService;
import org.jeecg.modules.system.service.ISysRoleAppService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.vo.ApplicationGroupVo;
import org.jeecg.modules.system.vo.ApplicationListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 应用
 * @Author: jeecg-boot
 * @Date: 2024-07-08
 * @Version: V1.0
 */
@Api(tags = "应用")
@RestController
@RequestMapping("/application")
@Slf4j
public class ApplicationController extends JeecgController<Application, IApplicationService> {
    @Autowired
    private IApplicationService applicationService;
    //@Autowired
    //private ISysDictItemService sysDictItemService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysRoleAppService sysRoleAppService;

    /**
     * 分页列表查询
     *
     * @param application
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "应用-分页列表查询")
    @ApiOperation(value = "应用-分页列表查询", notes = "应用-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<Application>> queryPageList(Application application,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<Application> queryWrapper = QueryGenerator.initQueryWrapper(application, req.getParameterMap());
        Page<Application> page = new Page<Application>(pageNo, pageSize);
        IPage<Application> pageList = applicationService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 查看应用分组信息
     *
     * @return
     */
    @AutoLog(value = "应用-应用-查看应用分组信息")
    @ApiOperation(value = "应用-查看应用分组信息", notes = "应用-查看应用分组信息")
    @GetMapping(value = "/queryAppGroupList")
    public Result<ApplicationGroupVo> queryAppGroupList() {
        Result<ApplicationGroupVo> error = Result.ok();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, sysUser.getId());
        queryWrapper.select(SysUserRole::getRoleId);
        List<SysUserRole> sysUserRoleList = sysUserRoleService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(sysUserRoleList)) {
            List<String> roleIdList = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            LambdaQueryWrapper<SysRoleApp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(SysRoleApp::getRoleId, roleIdList);
            lambdaQueryWrapper.select(SysRoleApp::getAppId);
            List<SysRoleApp> sysRoleAppList = sysRoleAppService.list(lambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(sysRoleAppList)) {
                List<String> appIdList = sysRoleAppList.stream().map(SysRoleApp::getAppId).collect(Collectors.toList());
                LambdaQueryWrapper<Application> appQuery = new LambdaQueryWrapper<Application>().in(Application::getId, appIdList);
                List<Application> applicationList = applicationService.list(appQuery);
                if (CollectionUtils.isNotEmpty(applicationList)) {
                    Map<String, List<Application>> collect = applicationList.stream().collect(Collectors.groupingBy(Application::getApplicationGroupName));
                    ApplicationGroupVo applicationGroupVo = new ApplicationGroupVo(collect);
                    applicationGroupVo.getApplicationGroupMap().put("all", applicationList);
                    Result<ApplicationGroupVo> ok = Result.ok(applicationGroupVo);
                    return ok;

                }
                log.error("sysUser:{}", sysUser);
                log.error("sysRoleAppList:{}", sysRoleAppList);
                error.setMessage("应用查询为空");
                return error;
            } else {
                error.setMessage("用户对应的角色没有关联的应用");
                return error;
            }

        } else {
            error.setMessage("用户没有应用的角色权限");
            return error;

        }

    }


    /**
     * 查看应用分组信息
     *
     * @return
     */
    @AutoLog(value = "应用-查看用户权限下的应用列表")
    @ApiOperation(value = "应用-查看用户权限下的应用列表", notes = "应用-查看用户权限下的应用列表")
    @GetMapping(value = "/queryAppList")
    public Result<List<ApplicationListVo>> queryAppList() {
        Result<List<ApplicationListVo>> error = Result.ok();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, sysUser.getId());
        queryWrapper.select(SysUserRole::getRoleId);
        List<SysUserRole> sysUserRoleList = sysUserRoleService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(sysUserRoleList)) {
            List<String> roleIdList = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            LambdaQueryWrapper<SysRoleApp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(SysRoleApp::getRoleId, roleIdList);
            lambdaQueryWrapper.select(SysRoleApp::getAppId);
            List<SysRoleApp> sysRoleAppList = sysRoleAppService.list(lambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(sysRoleAppList)) {
                List<String> appIdList = sysRoleAppList.stream().map(SysRoleApp::getAppId).collect(Collectors.toList());
                LambdaQueryWrapper<Application> appQuery = new LambdaQueryWrapper<Application>().in(Application::getId, appIdList)
                        .select(Application::getId, Application::getApplicationCode, Application::getApplicationName,
                                Application::getApplicationTypeName, Application::getApplicationTypeDictId);
                List<Application> applicationList = applicationService.list(appQuery);
                if (CollectionUtils.isNotEmpty(applicationList)) {
                    List<ApplicationListVo> applicationListVos = BeanUtils.copyList(applicationList, ApplicationListVo::new);
                    Result<List<ApplicationListVo>> ok = Result.ok(applicationListVos);
                    return ok;
                }
                log.error("sysUser:{}", sysUser);
                log.error("sysRoleAppList:{}", sysRoleAppList);
                error.setMessage("应用查询为空");
                return error;
            } else {
                error.setMessage("用户对应的角色没有关联的应用");
                return error;
            }

        } else {
            error.setMessage("用户没有应用的角色权限");
            return error;

        }

    }

    /**
     * 查看应用分组信息
     *
     * @return
     */
    @AutoLog(value = "应用-查看应用列表")
    @ApiOperation(value = "应用-查看应用列表", notes = "应用-查看应用列表")
    @GetMapping(value = "/queryAllAppInfos")

    public Result<List<ApplicationListVo>> queryAllAppInfos() {
        try {
            Result<List<ApplicationListVo>> success = Result.ok();
            LambdaQueryWrapper<Application> lambdaQueryWrapper = new LambdaQueryWrapper<Application>()
                    .eq(Application::getDelFlag, CommonConstant.STATUS_NORMAL.toString())
                    .select(Application::getApplicationCode, Application::getApplicationName ,Application::getId);
            List<Application> applicationList = applicationService.list(lambdaQueryWrapper);
            if (CollectionUtils.isEmpty(applicationList)) {
                return success;
            }
            List<ApplicationListVo> applicationListVos = BeanUtils.copyList(applicationList, ApplicationListVo::new);
            Result<List<ApplicationListVo>> ok = Result.ok(applicationListVos);
            return ok;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 添加
     *
     * @param application
     * @return
     */
    @AutoLog(value = "应用-添加")
    @ApiOperation(value = "应用-添加", notes = "应用-添加")
    @RequiresPermissions("application:application:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Application application) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        application.setCreateBy(sysUser.getLoginName());
        application.setCreateTime(new Date());
        applicationService.save(application);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param application
     * @return
     */
    @AutoLog(value = "应用-编辑")
    @ApiOperation(value = "应用-编辑", notes = "应用-编辑")
    @RequiresPermissions("application:application:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody Application application) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        application.setUpdateBy(sysUser.getLoginName());
        application.setUpdateTime(new Date());
        applicationService.updateById(application);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "应用-通过id删除")
    @ApiOperation(value = "应用-通过id删除", notes = "应用-通过id删除")
    @RequiresPermissions("application:application:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        applicationService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "应用-批量删除")
    @ApiOperation(value = "应用-批量删除", notes = "应用-批量删除")
    @RequiresPermissions("application:application:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.applicationService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "应用-通过id查询")
    @ApiOperation(value = "应用-通过id查询", notes = "应用-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Application> queryById(@RequestParam(name = "id", required = true) String id) {
        Application application = applicationService.getById(id);
        if (application == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(application);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param application
     */
    @RequiresPermissions("application:application:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Application application) {
        return super.exportXls(request, application, Application.class, "应用");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("application:application:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Application.class);
    }


}
